package com.zhuozhengsoft.springbootpageoffice.controller;

import com.zhuozhengsoft.pageoffice.OpenModeType;
import com.zhuozhengsoft.pageoffice.PageOfficeCtrl;
import com.zhuozhengsoft.pageoffice.excel.SheetReader;
import com.zhuozhengsoft.pageoffice.excel.SheetWriter;
import com.zhuozhengsoft.pageoffice.excel.WorkbookReader;
import com.zhuozhengsoft.pageoffice.excel.WorkbookWriter;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@RequestMapping(value = "/DefinedNameCell")
public class DefinedNameCellController {

    @RequestMapping(value = "/Excel")
    public ModelAndView showWord(HttpServletRequest request, Map<String, Object> map) {
        PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);

        //定义Workbook对象
        WorkbookWriter workBook = new WorkbookWriter();
        //定义Sheet对象，"Sheet1"是打开的Excel表单的名称
        SheetWriter sheet = workBook.openSheet("Sheet1");
        sheet.openCellByDefinedName("testA1").setValue("Tom");
        sheet.openCellByDefinedName("testB1").setValue("John");

        poCtrl.setWriter(workBook);

        //打开excel文档
        poCtrl.webOpen("/doc/DefinedNameCell/test.xls", OpenModeType.xlsNormalEdit, "张三");
        map.put("pageoffice", poCtrl.getHtml());
        ModelAndView mv = new ModelAndView("DefinedNameCell/Excel");
        return mv;
    }


    @RequestMapping("/save")
    public void save(HttpServletRequest request, HttpServletResponse response, Map<String, Object> map) throws IOException {
        response.setCharacterEncoding("utf-8");//解决返回的数据中文乱码问题
        WorkbookReader workBook = new WorkbookReader(request, response);
        SheetReader sheet = workBook.openSheet("Sheet1");
        String content = "";
        content += "testA1：" + sheet.openCellByDefinedName("testA1").getValue() + "\r\n";
        content += "testB1：" + sheet.openCellByDefinedName("testB1").getValue() + "\r\n";
        /**
         * 实际开发中，一般获取数据区域的值后用来和数据库进行交互，比如根据刚才获取的数据进行数据库记录的新增，更新，删除等。
         * 此处为了给用户展示获取的数据内容，通过setCustomSaveResult将获取的数据区域的值返回到前端页面给用户检查执行的结果。
         * 如果只是想返回一个保存结果，可以使用比如：setCustomSaveResult("ok")，前端可以根据这个保存结果进行下一步逻辑处理。
         */
        workBook.setCustomSaveResult(content);
        workBook.close();
    }

}
